﻿<?php

include './wxconfig.php';

Class WX {

    public $access_token;
    public $time;
    public $access_token_url;
    public $fileurl;

    public function __construct($fileurl, $access_token_url) {
        $this->fileurl = $fileurl;
        $this->time = time();
        $this->access_token_url = $access_token_url;
        $this->isfile($this->fileurl);
    }

    public function raccess_token() {
        return $this->access_token;
    }

    public function jsonto($content, $flag = TRUE) {
        return json_decode($content, $flag);
    }

    public function isfile($fileurl) {
        if (file_exists($fileurl)) {
            $file = fopen($fileurl, "r");
            $text = fread($file, 1000);
            fclose($file);
            $data = $this->jsonto($text);
            if (isset($data['expires_in']) && isset($data['time']) && $this->time < $data['expires_in'] + $data['time']) {
                $this->access_token = $data['access_token'];
            } else {
                $this->startOpen($fileurl);
            }
        } else {
            $this->startOpen($fileurl);
        }
    }

//
//第一次打开写入access_token;
    public function startOpen($fileurl) {
        $file = fopen($fileurl, "w");
        $result = file_get_contents($this->access_token_url);
        $result = json_decode($result, TRUE);
        $result['time'] = $this->time;
        $this->access_token = $result['access_token'];
        $result = json_encode($result);
        fwrite($file, $result);
        fclose($file);
    }

}
$wx = new WX($ageingurl,$access_token_url);




